package com.jxb.exception.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String s = "";
        if (e instanceof FlowException) {
            s = "接口限流了";
            System.out.println("接口限流了");
        }
        if (e instanceof DegradeException) {
            s = "服务降级了";
            System.out.println("服务降级了");
        }
        if (e instanceof ParamFlowException) {
            s = "热点参数限流了";
            System.out.println("热点参数限流了");
        }
        if (e instanceof SystemBlockException) {
            s = "触发系统保护规则了";
            System.out.println("触发系统保护规则了");
        }
        if (e instanceof AuthorityException) {
            s = "授权规则不通过";
            System.out.println("授权规则不通过");
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), JSON.toJSON(s));
    }
}
